import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from '../utils/axios'
import router from '../router'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 从localStorage恢复用户信息
  const storedUserInfo = localStorage.getItem('userInfo')
  const initialUserInfo = storedUserInfo ? JSON.parse(storedUserInfo) : {
    userId: '',
    username: '',
    phone: '',
    email: ''
  }

  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(initialUserInfo)

  const login = async (username: string, password: string) => {
    try {
      const response = await axios.post('/user/login', {
        username,
        password
      })
      if (response.data.code === 1) {  // 检查成功状态码
        const { data } = response.data
        token.value = data.token
        userInfo.value = {
          userId: data.userId,
          username: data.username,
          phone: data.phone,
          email: data.email
        }
        // 保存token和用户信息到localStorage
        localStorage.setItem('token', data.token)
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        ElMessage.success('登录成功')
        router.push('/home/resources')
        return true
      } else {
        ElMessage.error(response.data.msg || '登录失败')
        return false
      }
    } catch (error: any) {
      const errorMsg = error.response?.data?.msg || error.message || '登录失败'
      ElMessage.error(errorMsg)
      return false
    }
  }

  const register = async (formData: FormData) => {
    try {
      const response = await axios.post('/user/register', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      return true
    } catch (error: any) {
      const errorMsg = error.response?.data?.msg || error.message || '注册失败'
      ElMessage.error(errorMsg)
      return false
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = {
      userId: '',
      username: '',
      phone: '',
      email: ''
    }
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    router.push('/login')
  }

  return {
    token,
    userInfo,
    login,
    register,
    logout
  }
}) 